var t = getApp(), e = t.requirejs('core');
Page({
  data: {
    // 数据列表
    datalist: [],
    address: {},
    // 数量列表
    count: [],
    // 用于控制复选框状态
    checkbox: [],
    // 用于控制全选状态
    isall: false,
    // 用于控制按钮状态
    isdisable: true
  },
  onLoad(options) {
    this.get_data();
  },
  get_data() {
    e.get("zstock/stock", {}, res => {
      // 数据
      console.log(res);
      var count = [];
      var checkbox = [];
      for (let index = 0; index < res.stocks.length; index++) {
        count.push(1);
        checkbox.push(false);
      }
      this.setData({datalist: res.stocks, count: count, checkbox: checkbox, address: res.address})
    })
  },
  onShow() {
    var address = t.getCache("orderAddress")
    this.setData({address: address})
  },
  // 修改复选框
  checkbox(params) {
    var index = params.currentTarget.dataset.index;
    var checkbox = this.data.checkbox;
    checkbox[index] = !checkbox[index];
    // 判断是否全部都为真
    if (checkbox.indexOf(false) == -1) {this.setData({isall: true})} else {this.setData({isall: false})}
    // 判断是否有真
    if (checkbox.indexOf(true) == -1) {this.setData({isdisable: true})} else {this.setData({isdisable: false})}
    this.setData({checkbox: checkbox});
  },
  // 全选
  all() {
    this.setData({isall: !this.data.isall});
    var checkbox = this.data.checkbox;
    for (let index = 0; index < checkbox.length; index++) {
      checkbox[index] = this.data.isall;
    }
    // 判断是否有真
    this.setData({checkbox: checkbox})
    if (checkbox.indexOf(true) == -1) {this.setData({isdisable: true})} else {this.setData({isdisable: false})}
  },
   // 减
   sub(params) {
    var index = params.currentTarget.dataset.index;
    let count = this.data.count;
    if (count[index] == 1) {
      wx.showToast({title: '最小一个', icon: 'none'})
      return
    } else {
      count[index] = count[index] - 1;
      this.setData({count: count})
    }
  },
  // 加
  add(params) {
    var index = params.currentTarget.dataset.index;
    let count = this.data.count;
    count[index] = count[index] + 1;
    this.setData({count: count})
  },
  // 提交
  submit(params) {
    let that = this;
    var value = params.detail.value.checkbox;
    if (that.address) {
      wx.showToast({title: '请选择收货地址', icon: 'none'});
      return
    }
    var str = []
    let list = that.data.datalist;
    for (let index = 0; index < value.length; index++) {
      str.push(list[value[index]].sid + ':' + list[value[index]].id + ":" + that.data.count[value[index]])
    }
    var data = {
      addressid: this.data.address.id,
      str: str.join(',')
    }
    // console.log(data);return;
    e.get("zstock/stock/stockout", data, res => {
      if (res.status == 1) {
        wx.showToast({title: '出库成功', icon: 'none'});
        wx.navigateTo({
          url: '/pages/order/index?status=1',
        })
        this.get_data();
      } else {
        wx.showToast({title: res.result.message, icon: 'none'})
      }
    })
  },
})